package com.cn.web;

import com.cn.entity.Goods;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: chenyuncong
 * @Date: 2020/6/23 10:27
 */
@RestController
@RequestMapping("redis")
public class RedisTemplateController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LoadingCache<String, String>  loadingCache;

    @Autowired
    private LoadingCache<Long, Goods> getGoodsCache;

    @GetMapping("setCache")
    public String setCache(String key,String val){
        loadingCache.put(key,val);
        return "OK";
    }

    @GetMapping("getCache")
    public String getCache(String key){
        return loadingCache.get(key);
    }

    @GetMapping("getGoodsCache")
    public Goods getGoodsCache(Long id){
        return getGoodsCache.get(id);
    }

    @GetMapping("set")
    public boolean set(){
        redisTemplate.opsForValue().set("aaaaa","小明同学");

//        redisTemplate.opsForValue().increment()
//        redisTemplate.opsForValue().decrement()
        return true;
    }

    @GetMapping("get")
    public Object get(){

        return redisTemplate.opsForValue().get("aaaaa");
    }

    @GetMapping("incr")
    public long incr(String key){
        return redisTemplate.opsForValue().increment(key);
    }

    @GetMapping("increment")
    public long increment(String key,long val){
        return redisTemplate.opsForValue().increment(key,val);
    }

    @GetMapping("deleteKey")
    public boolean deleteKey(String key){
        return redisTemplate.delete(key);
    }

    @GetMapping("test01")
    public void test01(){
        for(int i=0;i<50;i++){
            new Thread(() -> {
                long startTime=System.currentTimeMillis();
                for(int j=0;j<100;j++){
                    redisTemplate.opsForValue().increment("incrAdd");
                }
                System.out.println(System.currentTimeMillis()-startTime);
            }).start();
        }
//        System.out.println();
//        long startTime=System.currentTimeMillis();
//        for(int j=0;j<5000;j++){
//            redisTemplate.opsForValue().increment("incrAdd");
//        }
//        System.out.println(System.currentTimeMillis()-startTime);
    }
}
